import { createWebHistory, createRouter } from 'vue-router'
import { getToken, removeToken } from '@/utils/token';
import useUserStore from '@/store/modules/user'
// 公共路由
export const constantRoutes = [
    {
        path: '',
        redirect: '/login',
        hidden: true
    },
    {
        path: '/login',
        component: () => import('@/views/login.vue'),
        hidden: true
    },
    {
        path: '/me',
        component: () => import('@/views/jianli/index.vue'),
        hidden: true
    },
    {
        path: '/redirect',
        component: () => import('@/views/index.vue'),
        hidden: true,
        children: [
            {
                path: '/redirect/:path(.*)',
                component: () => import('@/views/redirect.vue')
            }
        ]
    },
    {
        path: '/index',
        component: () => import('@/views/index.vue'),
        hidden: true
    },
    {
        path: '/test',
        component: () => import('@/components/calc.vue'),
        hidden: true
    },

]


const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    },
});





const whiteList = ['/login_bak', '/login_back', '/login', '/auth-redirect', '/test', '/register'];  //白名单，这些不需要登录也可以访问
router.beforeEach(async (to, from, next) => {
    // console.log(to, router.getRoutes());

    if (getToken()) {
        if (useUserStore().name == '') {

            //刷新造成pina数据丢失 直接重登 前后台都没有缓存处理
            removeToken()
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        }
        else
            next()
    }
    else {

        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {

            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页

        }
    }

})
export default router;